package com.ms.mishitong.inceptor;

import cn.hutool.core.bean.BeanUtil;

import com.ms.mishitong.dto.UserDTO;
import com.ms.mishitong.entity.User;
import com.ms.mishitong.utils.RedisConstants;
import com.ms.mishitong.utils.ThroadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
public class LoginInceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public LoginInceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         //获取请求头中的token
      String token =   request.getHeader("Authorization");
      log.info("Authorization为{}",token);
      //如果token为空，拦截并返回401
      if(token == null||  token.isEmpty()){
           response.setStatus(401);
           return false;
      }

        //基于token获取redis中的用户
       Map<Object,Object> map  =  stringRedisTemplate.opsForHash().entries(RedisConstants.LOGIN_USER_KEY+token);

        //判断用户是否存在
        if(map == null|| map.isEmpty()){
            //不存在，拦截并且返回401
             response.setStatus(401);
             return false;

        }
        //将查询到的Hash数据转为UserDto对象
        UserDTO userDTO = BeanUtil.fillBeanWithMap(map,new UserDTO(),false);
        //存在，将用户信息保存在ThroadLocal中
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        ThroadLocal.set(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThroadLocal.remove();
    }
}
